package com.flextribe.ui
{
	import flash.events.IEventDispatcher;
	import flash.events.KeyboardEvent;
	
	public class KeyStrokeBinder
	{
		
		public var target:IEventDispatcher = null;
		public var handler:Function = null;
		public var args:Array = null;
		public var keyCode:uint = 0;
		public var ctrlKey:Boolean = false;
		public var altKey:Boolean = false;
		public var shiftKey:Boolean = false;
		
		public function KeyStrokeBinder(
			target:IEventDispatcher=null,
			handler:Function=null, args:Array = null, 
			keyCode:int=0, ctrlKey:Boolean=false, altKey:Boolean=false, shiftKey:Boolean=false){
			
			this.target = target;
			this.handler = handler;
			this.keyCode = keyCode;
			this.ctrlKey = ctrlKey;
			this.altKey = altKey;
			this.shiftKey = shiftKey;
				
		}

		public function attach():void{
			if(this.target != null && this.handler != null){
				target.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler, false, 0, true);
			}
		}
		public function detach():void{
			if(target != null && this.handler != null){
				target.removeEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
			}
		}

		private function keyHandler(e:KeyboardEvent):void{
			if( this.handler==null ) return;
			if( (e.keyCode==this.keyCode && e.altKey==this.altKey && e.ctrlKey==this.ctrlKey && e.shiftKey==this.shiftKey) || this.keyCode==0 ) {
				this.handler.apply( null, this.args );
			}
		}
		
	}
}